﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VDataAdapter
{
    public class MessageHistories
    {
        private ArrayList _histories;
        
        /// <summary>
        /// Number of items that were clear
        /// </summary>
        private int _removedItemsCount;
        private int _maxStorage;
        private int _minBufferSize;
        
        /// <summary>
        /// maxStorage: maximum index store in RAM
        /// </summary>
        /// <param name="messageHistories"></param>
        /// <param name="maxStorage"></param>
        public MessageHistories(ArrayList messageHistories, int maxStorage, int minBufferSize)
        {
            _removedItemsCount = 0;
            _histories = messageHistories;
            _maxStorage = maxStorage;
            _minBufferSize = minBufferSize;
        }

        public string GetMessage(int index)
        {
            string msg;
            try
            {
                msg = _histories[index - _removedItemsCount] as string;
            }
            catch(Exception ex)
            {
                throw new Exception("Might try to access item not exist anymore");
            }
            return msg;
        }

        public int PhysicalCount
        {
            get { return _histories.Count; }
        }

        public int Count
        {
            get { return _histories.Count + _removedItemsCount; }
        }

        /// <summary>
        /// Clear the list
        /// </summary>
        public void Clear()
        {
            _histories.Clear();
            _removedItemsCount = 0;
        }
        
        public void Add(string message)
        {
            _histories.Add(message);
            if (_histories.Count > _maxStorage)
            {
                ReduceUntilSize(_minBufferSize);
            }
        }

        /// <summary>
        /// Clear history until min buffer size
        /// </summary>
        private void ReduceUntilSize(int minSize)
        {
            Console.WriteLine("Reducing size of memhistories: current size " + _histories.Count + " to: " +minSize);
            try
            {
                int removedItemsCount = _histories.Count - minSize;
                _histories.RemoveRange(0, removedItemsCount);
                _removedItemsCount += removedItemsCount;
            }
            catch (Exception)
            {

                throw new Exception("out of range while trying to remove size");
            }
            
        }
    }
}
